package cn.lg.soar.boot.config;

import cn.lg.soar.core.manager.IAccessTokenValidator;
import cn.lg.soar.core.manager.PermitLevelManager;
import cn.lg.soar.mvc.handler.AuthFilter;
import cn.lg.soar.system.api.manager.AuthenticationManager;
import cn.lg.soar.system.api.model.AuthProps;
import cn.lg.soar.system.api.service.IUserApi;
import jakarta.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;

/**
 * 当前用户过滤器（主要拥于清除当前用户，释放内存）
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Configuration
public class AuthFilterConfig {

    @Lazy
    @Autowired
    private IUserApi userApi;
    @Lazy
    @Autowired
    private AuthenticationManager authenticationManager;
    @Lazy
    @Autowired
    private IAccessTokenValidator accessTokenValidator;
    @Lazy
    @Autowired
    private AuthProps authProps;

    @Bean
    public FilterRegistrationBean<Filter> authFilterBean() {
        // 权限级别管理器
        PermitLevelManager permitLevelManager = new PermitLevelManager(authProps.getDefault());
        authProps.getPermitLevel().forEach(permitLevelManager::setLevelPatterns);
        permitLevelManager.setPermitUserTypes(authProps.getPermitUserType());
        // 使用内置权限过滤器，可按自己需要实现自己的权限过滤器
        AuthFilter authFilter = new AuthFilter(
                permitLevelManager,
                accessTokenValidator,
                authenticationManager,
                userApi::isSuperAdministrator
        );
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(authFilter);
        registration.addUrlPatterns("/*");
        registration.setName("authFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 200);
        return registration;
    }


}
